package com.sino.operation.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.Map;


@Component
public class JwtUtil {

    private  String SECRET="QWHTASDAFSADGATASADF4444TASDT566ASTASDFASTASDFASGASTASDFATA2TASDTASDFASGAS4";


    private  Integer EXPIRE_TIME=60*24;

    /**
     *   由字符串生成secret;
     * @return
     */
    public  SecretKey generalKey(){
        SecretKey sk = Keys.hmacShaKeyFor(SECRET.getBytes());
        return sk;
    }

    /**
     *   生成Token
     * @param maps
     * @param
     * @return
     */
    public  String createJwt(Map<String, Object> maps) {
        JwtBuilder jwtBuilder = Jwts.builder().signWith(generalKey(), SignatureAlgorithm.HS256);
        if(maps != null && maps.size() > 0){jwtBuilder.setClaims(maps);}
        String token = jwtBuilder.setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE_TIME*60*1000))
                .compact();
        return token;
    }

    /**
     *   生成Token
     * @param
     * @param
     * @return
     */
    public String createJwt() {
        return createJwt(null);
    }

    /**
     *   解析Token，获取注册信息
     * @param
     * @return
     */
    public Claims parseJwt(String token) {
        return Jwts.parserBuilder().setSigningKey(generalKey()).build().parseClaimsJws(token).getBody();
    }

    /**
     *   获取token失效时间
     * @param token
     * @return
     * @throws Exception
     */
    public Date getExpirationDateFromToken(String token) {
        return parseJwt(token).getExpiration();
    }

    /**
     *   验证token是否过期失效
     * @param token
     * @return
     * @throws Exception
     */
    public boolean isTokenExpired (String token) {
        Date expirationTime = getExpirationDateFromToken(token);
        return expirationTime.before(new Date());
    }

    /**
     *   获取jwt发布时间
     * @param token
     * @return
     * @throws Exception
     */
    public long getIssuedAtDateFromToken(String token){
        return parseJwt(token).getIssuedAt().getTime();
    }
    public String getSecret() {
        return SECRET;
    }

    public void setSecret(String secret) {
        this.SECRET = secret;
    }

    public Integer getExpire() {
        return EXPIRE_TIME;
    }

    public void setExpire(Integer expire) {
        this.EXPIRE_TIME = expire;
    }
}
